<?php
session_start();
include_once "checkAdmin.php";
$carName = $_POST['carname'];
$description = $_POST['description'];
include_once "conn.php";

if ($_FILES["carpic"]["error"] >0 and $_FILES["carpic"]["error"] <= 4) {
    echo "<script>alert('上传文件出错或未选择文件');history.go(-1);</script>";
    exit;
}

if (!empty($_FILES["carpic"]["name"])) { //判断是否有选择图片
    if($_FILES["carpic"]["size"] > 2048*1024){  //文件尺寸超过2MB
        echo "<script>alert('上传文件大小最多2MB');history.go(-1);</script>";
        exit;
    }
    $path = "image/"; //上传路径
    if (!file_exists($path)) {//检查是否有该文件夹，如果没有就创建，并给予最高权限
        mkdir($path, 0700);
    }//END IF
    //允许上传的文件格式
    $tp = array("image/gif", "image/pjpeg", "image/jpeg", "image/jpg", "image/png");
    //检查上传文件是否是允许上传的类型
    if (!in_array($_FILES["carpic"]["type"], $tp)) {
        echo "<script>alert('上传图片只支持JPG、GIF、PNG格式');history.go(-1);</script>";
        exit;
    }//END IF
    $ext = end(explode('.',$_FILES["carpic"]["name"]));  //得到扩展名
    $today = date("YmdHis") . rand(1000,9999); //获取时间并赋值给变量
    $img = $today .".". $ext; //得到新的文件名
    $file2 = $path . $img; //图片的完整路径     $path.date("YmdHis") . rand(1000,9999).".".$ext
    $result = move_uploaded_file($_FILES["carpic"]["tmp_name"], $file2);
    //exit;
    if(!$result){
        echo "<script>alert('上传文件出错');history.go(-1);</script>";//注意，此处传递给move_uploaded_file的第一个参数为上传到服务器上的临时文件
        exit;
    }
}

$sql = "insert into car (carname,description,carpic) values ('$carName','$description','$file2')";
$result = mysqli_query($conn, $sql);

if ($result) {
    echo "<script>alert('添加成功');location.href='admin.php';</script>";
    exit;
} else {
    echo "<script>alert('添加失败');location.href='admin.php';</script>";
    exit;
}